import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    meta: {
      title: '首页',
      keepAlive: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      hideTabBar: true
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile.vue'),
    meta: {
      title: '个人中心',
      keepAlive: true
    }
  },
  {
    path: '/network-test',
    name: 'NetworkTest',
    component: () => import('@/views/NetworkTest.vue'),
    meta: {
      title: '网络测试',
      hideTabBar: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  
  // 检查用户是否已登录
  const token = localStorage.getItem('token')
  const user = localStorage.getItem('user')
  
  // 如果访问登录页面或网络测试页面，直接允许
  if (to.path === '/login' || to.path === '/network-test') {
    next()
    return
  }
  
  // 如果没有token或用户信息，重定向到登录页
  if (!token || !user) {
    next('/login')
    return
  }
  
  // 已登录，允许访问
  next()
})

export default router
